/**
 *  生成有向图
 */


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 将邻接矩阵转成DOT源码
 */

public class AdjacencyMatrix2DOT2Image {
    private String fileDir;

    public AdjacencyMatrix2DOT2Image() {
        this.fileDir = "D:\\Desktop\\HIT\\SoftwareProject\\Lab1\\src\\Image\\";
    }

    public void showDirectedGraph(AdjacencyMatrix adjacencyMatrix) {
        String DOT = "digraph G {\n";

        for (int i = 0; i < adjacencyMatrix.getNumVertices(); i++) {
            for (int j = 0; j < adjacencyMatrix.getNumVertices(); j++) {
                if (adjacencyMatrix.getWeight(i, j) != 0) {
                    DOT += ("    " + adjacencyMatrix.getNameFromIndex(i) + " -> " + adjacencyMatrix.getNameFromIndex(j)
                            + " [label=\"" + adjacencyMatrix.getWeight(i, j) + "\"];\n");
                }
            }
        }
        DOT += "}";

        File file = writeDotSourceToFile(DOT);
        convertDotToGraph(file, "png");
    }

    private static File writeDotSourceToFile(String dotSource) {
        try {
            File tempDotFile = File.createTempFile("graph_", ".dot");
            FileWriter writer = new FileWriter(tempDotFile);
            writer.write(dotSource);
            writer.close();
            return tempDotFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void convertDotToGraph(File dotFile, String format) {
        String outputFilePath = this.fileDir + "DOT" + "." + format;
        String[] args = {"dot", "-T" + format, dotFile.getAbsolutePath(), "-o", outputFilePath};
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(args);
            Process process = processBuilder.start();
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Directed graph generated successfully!");
        System.out.println("Be placed in: " + outputFilePath);
    }
}
